package com.yourname.www.util;

import com.yourname.www.entity.Student;

import javax.swing.*;
import javax.swing.table.JTableHeader;
import javax.swing.table.TableColumn;
import java.util.Calendar;
import java.util.Enumeration;
import java.util.Vector;

public class Tools {

	//获取年级
		public static String[] CreateGrade(){
			String[]  year = new String[5];
			Calendar c = Calendar.getInstance();
			int Year = c.get(Calendar.YEAR);
			year[0] = "--请选择--";
			for(int i=1;i<=4;i++){
				year[i] = (String.valueOf(Year--));
			}
			return year;
			
		}

	/**
	 * 方法一 自适应 好用 效率差
	 * @param jTable
	 */
	public static void fitTableColWidth(JTable jTable){
		jTable.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
		JTableHeader header = jTable.getTableHeader();
		int rowCount = jTable.getRowCount();
		Enumeration<TableColumn> columns = jTable.getColumnModel().getColumns();
		while (columns.hasMoreElements()) {
			TableColumn column = columns.nextElement();
			int columnIndex = header.getColumnModel().getColumnIndex(column.getIdentifier());
			int width = (int) header.getDefaultRenderer().getTableCellRendererComponent(jTable, column.getIdentifier(), false, false, -1, columnIndex).getPreferredSize().getWidth();
			for(int row=0;row<rowCount;row++){
				int preferredWidth = (int) jTable.getCellRenderer(row, columnIndex).getTableCellRendererComponent(jTable, jTable.getValueAt(row, columnIndex), false, false, row, columnIndex).getPreferredSize().getWidth();
				width = Math.max(width,preferredWidth);
			}
			header.setResizingColumn(column);
			column.setWidth(width+jTable.getIntercellSpacing().width);
		}


	}

	/**
	 * 方法二 直接指定宽度更高效
	 * @param jTable
	 * @param lenArr
	 */
	public static void setTableColWidth(JTable jTable,int[] lenArr){
		jTable.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
		JTableHeader header = jTable.getTableHeader();
		int rowCount = jTable.getRowCount();
		Enumeration<TableColumn> columns = jTable.getColumnModel().getColumns();
		int i=0;
		while (columns.hasMoreElements()) {
			TableColumn column = columns.nextElement();
			int width = lenArr[i];
			header.setResizingColumn(column);
			column.setWidth(width+jTable.getIntercellSpacing().width);
			i++;
		}


	}

}
